package com.jshoperxms.controller.api.langdu;

import com.jshoperxms.Response;
import com.jshoperxms.controller.api.langdu.vo.YdTeamTargetTVo;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.*;
import com.jshoperxms.service.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 2019/2/22.
 * Des:
 */
@RestController
@RequestMapping("/api/teamtarget")
public class YdTeamTargetController extends BaseTController {

    @Resource
    private YdTeamTargetTService ydTeamTargetTService;

    @Resource
    private MemberTService memberTService;

    @Resource
    private YdTeamTService ydTeamTService;

    @Resource
    private YdTeamTargetMemberTService ydTeamTargetMemberTService;



    /**
     * 加入公开的目标
     * @param rq
     * @return
     */
    @RequestMapping(value="/joinPublicTarget",method= RequestMethod.POST)
    public ResponseEntity joinPublicTarget(@RequestBody YdTeamTargetMemberT rq) {
        Map<String, Object> responsedata = new HashMap<>();
        if (StringUtils.isNotBlank(rq.getTargetid())) {
            //检查是否加入过该目标
            Criterion criterion = Restrictions.and(Restrictions.eq("targetid", rq.getTargetid())).add(Restrictions.eq("wxopenid",rq.getWxopenid()));
            YdTeamTargetMemberT ydTeamTargetMemberT = this.ydTeamTargetMemberTService.findOneByCriteria(YdTeamTargetMemberT.class, criterion);
            if (ydTeamTargetMemberT != null) {
                responsedata.put(TagWords.SUCCESS, false);
                responsedata.put(TagWords.MSG, "已加入目标");
            } else {
                //获取目标信息
                YdTeamTargetT ydTeamTargetT=this.ydTeamTargetTService.findByPK(YdTeamTargetT.class,rq.getTargetid());
                Criterion criterion1 = Restrictions.eq("wxopenid", rq.getWxopenid());
                MemberT memberT = this.memberTService.findOneByCriteria(MemberT.class, criterion1);
                if (ydTeamTargetT!=null&&memberT != null) {
                    YdTeamTargetMemberT bean = new YdTeamTargetMemberT();
                    bean.setId(PrimaryKey.get().toString());
                    bean.setTmnick(memberT.getNick());
                    bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                    bean.setCreatorid("0");
                    bean.setUpdatetime(DateTools.getSystemTimeLong());
                    bean.setCreatetime(DateTools.getSystemTimeLong());
                    bean.setVersiont(1);
                    bean.setMemberid(memberT.getId());
                    bean.setWxopenid(memberT.getWxopenid());
                    bean.setTargetid(rq.getTargetid());
                    bean.setTeamid("0");
                    bean.setAvatarurl(memberT.getHeadpath());
                    bean.setCurrenttimes(0);
                    bean.setIsleader(0);
                    this.ydTeamTargetMemberTService.save(bean);
                    responsedata.put(TagWords.BEAN, bean);
                    responsedata.put(TagWords.SUCCESS, true);
                    updatePubliceTargetMemberCount(ydTeamTargetT);
                }
            }
        } else {
            responsedata.put(TagWords.SUCCESS, false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }

    private void updatePubliceTargetMemberCount(YdTeamTargetT bean){
        bean.setUpdatetime(DateTools.getSystemTimeLong());
        bean.setCurrentmember(bean.getCurrentmember()+1);
        this.ydTeamTargetTService.update(bean);
    }

    /**
     * 保存公开的任务目标
     * @param rq
     * @return
     */
    @RequestMapping(value="/savePublicTarget",method= RequestMethod.POST)
    public ResponseEntity savePublicTarget(@RequestBody YdTeamTargetTVo rq) throws ParseException {
        Map<String, Object> responsedata = new HashMap<>();
        if(StringUtils.isNotBlank(rq.getWxopenid())){
            Criterion criterion1= Restrictions.eq("wxopenid",rq.getWxopenid());
            MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion1);
            if(memberT!=null){
                YdTeamTargetT bean=new YdTeamTargetT();
                bean.setId(PrimaryKey.get().toString());
                bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                bean.setCreatetime(DateTools.getSystemTimeLong());
                bean.setCreatorid("0");
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(1);
                bean.setTeamid(StaticKey.EMPTY);
                bean.setMemberid(memberT.getId());
                bean.setWxopenid(rq.getWxopenid());
                bean.setTargetname("#"+rq.getTargetname()+"#");
                bean.setTargetnote(rq.getTargetnote());
                bean.setTargettype(rq.getTargettype());
                bean.setTargettimes(rq.getTargettimes());
                bean.setFinishtargettime(DateTools.formatStringDateYYYYMMDD2Long(rq.getTargetenddate()));
                bean.setRewardcontent(rq.getRewardcontent());
                bean.setTargetstatus("1");//未开始目标
                bean.setTargetbegintime(0L);//任务未开始
                bean.setTargetendtime(0L);
                bean.setTargetcategoryid(rq.getTargetcategoryid());
                bean.setTargetcategoryname(rq.getTargetcategoryname());
                bean.setCurrentmember(1);
                this.ydTeamTargetTService.save(bean);
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                saveLeaderToPublicTarget(memberT,bean);
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG, "nomember");
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }



    /**
     * 把队长放到公开目标里
     * @param memberT
     * @param teamTargetT
     */
    private void saveLeaderToPublicTarget(MemberT memberT, YdTeamTargetT teamTargetT){
        YdTeamTargetMemberT bean=new YdTeamTargetMemberT();
        bean.setId(PrimaryKey.get().toString());
        bean.setTmnick(memberT.getNick());
        bean.setStatus(BaseEnums.DataUsingState.USING.getState());
        bean.setCreatetime(DateTools.getSystemTimeLong());
        bean.setCreatorid("0");
        bean.setUpdatetime(DateTools.getSystemTimeLong());
        bean.setVersiont(1);
        bean.setMemberid(memberT.getId());
        bean.setWxopenid(memberT.getWxopenid());
        bean.setTargetid(teamTargetT.getId());
        bean.setTeamid(teamTargetT.getTeamid());
        bean.setAvatarurl(memberT.getHeadpath());
        bean.setCurrenttimes(0);
        bean.setIsleader(1);
        this.ydTeamTargetMemberTService.save(bean);

    }


    /**
     * 把队长放到小队目标里
     * @param memberT
     * @param teamTargetT
     */
    private void saveLeaderToTeamTarget(MemberT memberT, YdTeamTargetT teamTargetT){
        YdTeamTargetMemberT bean=new YdTeamTargetMemberT();
        bean.setId(PrimaryKey.get().toString());
        bean.setTmnick(memberT.getNick());
        bean.setStatus(BaseEnums.DataUsingState.USING.getState());
        bean.setCreatetime(DateTools.getSystemTimeLong());
        bean.setCreatorid("0");
        bean.setUpdatetime(DateTools.getSystemTimeLong());
        bean.setVersiont(1);
        bean.setMemberid(memberT.getId());
        bean.setWxopenid(memberT.getWxopenid());
        bean.setTargetid(teamTargetT.getId());
        bean.setTeamid(teamTargetT.getTeamid());
        bean.setAvatarurl(memberT.getHeadpath());
        bean.setCurrenttimes(0);
        this.ydTeamTargetMemberTService.save(bean);

    }


    /**
     * 查询目标公园首页数据
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTargetIndexResult",method= RequestMethod.POST)
    public ResponseEntity findTargetIndexResult(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        int currentPage=rq.getStart();
        int lineSize=rq.getLength();
        if(StringUtils.equals("all",rq.getTargetcategoryname())){
            Criterion criterion=Restrictions.and(Restrictions.eq("targetstatus","1")).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("targettype","2"));
            int recrods=this.ydTeamTargetTService.count(YdTeamTargetT.class,criterion).intValue();
            List<YdTeamTargetT> list=this.ydTeamTargetTService.findByCriteriaByPage(YdTeamTargetT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
            rq.setRecordsTotal(recrods);
            responsedata.put("results",list);
            responsedata.put("start",rq.getNextPageNo());
            responsedata.put("totalPage",rq.getTotalPage());
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            Criterion criterion=Restrictions.and(Restrictions.eq("targetcategoryname",rq.getTargetcategoryname())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("targetstatus","1")).add(Restrictions.eq("targettype","2"));
            int recrods=this.ydTeamTargetTService.count(YdTeamTargetT.class,criterion).intValue();
            List<YdTeamTargetT> list=this.ydTeamTargetTService.findByCriteriaByPage(YdTeamTargetT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
            rq.setRecordsTotal(recrods);
            responsedata.put("results",list);
            responsedata.put("start",rq.getNextPageNo());
            responsedata.put("totalPage",rq.getTotalPage());
            responsedata.put(TagWords.SUCCESS,true);
        }
        return Response.success(responsedata);

    }

    /**
     * 查询小队目标列表
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamsTargets",method= RequestMethod.POST)
    public ResponseEntity findTeamsTargets(@RequestBody YdTeamTargetT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTeamid())){
            Criterion criterion=Restrictions.and(Restrictions.eq("teamid",rq.getTeamid())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
            List<YdTeamTargetT>list=this.ydTeamTargetTService.findByCriteria(YdTeamTargetT.class,criterion, Order.asc("targetstatus"));
            responsedata.put(TagWords.BEANLIST,list);
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    /**
     * 获取开始的目标和结束的目标
     * @param rq
     * @return
     */
    @RequestMapping(value="/findStartedTeamsTargets",method= RequestMethod.POST)
    public ResponseEntity findStartedTeamsTargets(@RequestBody YdTeamTargetT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTeamid())){
            Criterion criterion=Restrictions.and(Restrictions.eq("teamid",rq.getTeamid())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.ne("targetstatus","0"));
            List<YdTeamTargetT>list=this.ydTeamTargetTService.findByCriteria(YdTeamTargetT.class,criterion, Order.desc("targetstatus"));
            responsedata.put(TagWords.BEANLIST,list);
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    /**
     * 查询小队目标信息
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamTargetInfo",method= RequestMethod.POST)
    public ResponseEntity findTeamTargetInfo(@RequestBody YdTeamTargetT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            YdTeamTargetT bean=this.ydTeamTargetTService.findByPK(YdTeamTargetT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                YdTeamT ydTeamT=ydTeamTService.findByPK(YdTeamT.class,bean.getTeamid());
                if(ydTeamT!=null){
                    responsedata.put("leadername",ydTeamT.getLeadername());
                }
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    /**
     * 获取目标信息
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTargetInfo",method= RequestMethod.POST)
    public ResponseEntity findTargetInfo(@RequestBody YdTeamTargetT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            YdTeamTargetT bean=this.ydTeamTargetTService.findByPK(YdTeamTargetT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                Criterion criterion=Restrictions.and(Restrictions.eq("targetid",bean.getId())).add(Restrictions.eq("wxopenid",rq.getWxopenid()));
                YdTeamTargetMemberT ydTeamTargetMemberT=this.ydTeamTargetMemberTService.findOneByCriteria(YdTeamTargetMemberT.class
                ,criterion);
                if(ydTeamTargetMemberT!=null){
                    responsedata.put("isjointarget",true);
                }else{
                    responsedata.put("isjointarget",false);

                }
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    /**
     * 获取目标会员的打卡信息
     * @param rq
     * @return
     */
    @RequestMapping(value="/findPublicTargetMembersPTClock",method= RequestMethod.POST)
    public ResponseEntity findPublicTargetMembersPTClock(@RequestBody YdTeamTargetMemberT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTargetid())){
            Criterion criterion=Restrictions.and(Restrictions.eq("targetid",rq.getTargetid())).add(Restrictions.eq(TagWords.STATUS,BaseEnums.DataUsingState.USING.getState()));
            List<YdTeamTargetMemberT>beanlist=this.ydTeamTargetMemberTService.findByCriteria(YdTeamTargetMemberT.class,criterion, Order.desc(TagWords.CREATETIME));
            responsedata.put(TagWords.BEANLIST,beanlist);
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }

    @RequestMapping(value="/findMyJoinedTarget",method= RequestMethod.POST)
    public ResponseEntity findMyJoinedTarget(@RequestBody YdTeamTargetT rq) {
        Map<String, Object> responsedata = new HashMap<>();
        if (StringUtils.isNotBlank(rq.getWxopenid())) {

            String sql="select * from yd_team_target_t as ytt left join yd_team_target_member_t as yttm on ytt.id=yttm.targetid where yttm.wxopenid=:wxopenid  and ytt.targetstatus!=2";
            Map<String,Object>params=new HashMap<>();
            params.put("wxopenid",rq.getWxopenid());
            List<YdTeamTargetT>list=this.ydTeamTargetTService.queryBySql(YdTeamTargetT.class,sql,params);
            responsedata.put("results", list);
            responsedata.put(TagWords.SUCCESS, true);

        } else {
            responsedata.put(TagWords.SUCCESS, false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);

    }

}
